const baseURL = "http://localhost:8000/api/v1";
import {getData} from "./localstorage.js";
const method = {
    GET: "GET",
    POST: "POST",
    PUT: "PUT",
    DELETE: "DELETE"
}


const contentType = {
    JSON: "application/json;charset=UTF-8",
}

const getHeader = () => {
    const token = getData("currentUser")&& getData("currentUser").token
    let headers = {"Content-Type": contentType.JSON};
    if (token) {
        headers.Authorization = `Token ${token}`;
    }
    return headers;
}


/**
 * 封装请求
 */
const getRequest = async (url) => {
    const response = await fetch(baseURL + url, {
        method: method.GET,
        headers: getHeader()
    })
    return response.json();
}


const postRequest = async (url, body) => {
    const response = await fetch(baseURL + url, {
        method: method.POST,
        headers: getHeader(),
        body: JSON.stringify(body), //js对象->字符串
    })
    return response.json();
}
const deleteRequest = async (url, body) => {
    const response = await fetch(baseURL + url, {
        method: method.DELETE,
        headers: getHeader(),
        body: JSON.stringify(body), //js对象->字符串
    })
    return response.json();
}
const putRequest = async (url, body) => {
    const response = await fetch(baseURL + url, {
        method: method.PUT,
        headers: getHeader(),
        body: JSON.stringify(body), //js对象->字符串
    })
    return response.json();
}

export default {
    get: getRequest,
    post: postRequest,
    delete: deleteRequest,
    put: putRequest
}